package net.icez.upicme;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
//import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.widget.Toast;

import net.icez.twitter.PrivateData;


public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener, OnPreferenceChangeListener  {

	public static final String TAG = "UpicSharePreferences";
//	public static final String KEY_TWITTER_USERNAME = "twitter_username";
	public static final String KEY_USE_OAUTH = "use_oauth";

//	private EditTextPreference mUsername;
	private CheckBoxPreference mUseOAuth;
	
	protected OAuthService mOAuthService;
	protected boolean mAuthentiated = false;
	private ProgressDialog mProgressDialog;

    private static final int DIALOG_PERFORMING_OAUTH = 1;

    public static final int MSG_OAUTH_DONE = 1;
    public static final int MSG_OAUTH_SUCCESS = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
//		mUsername = (EditTextPreference) getPreferenceScreen().findPreference(KEY_TWITTER_USERNAME);
		mUseOAuth = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_USE_OAUTH);
		
		boolean useOAuth = mUseOAuth.isChecked();
		mUseOAuth.setOnPreferenceChangeListener(this);
		mOAuthService = new OAuthService(this);
		if (!useOAuth) {
			showDialog(DIALOG_PERFORMING_OAUTH);
			Thread thread = new Thread(mDoOAuth);
            thread.start();
		}
		
	}

	@Override
	protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);

            Uri uri = intent.getData();
            if (uri != null && uri.toString().startsWith(PrivateData.OAUTH_CALLBACK_URL)) {
                    showDialog(DIALOG_PERFORMING_OAUTH);
                    setIntent(intent);
                    Thread thread = new Thread(mCallbackOAuth);
                    thread.start();
            }
    }
	@Override
	protected void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {

	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if (preference.getKey().equals(KEY_USE_OAUTH)) {
			if (((Boolean)newValue).booleanValue()) {
				Thread thread = new Thread(mDoOAuth);
                thread.start();
                return false;
			}
		}
		return false;
	}

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_OAUTH_DONE:
            	try {
            		dismissDialog(DIALOG_PERFORMING_OAUTH);
            	} catch (Exception e) {
            		Log.d(TAG, "Caught MSG_OAUTH_SUCCESS exception " + e.getMessage());
            	}
                if (msg.obj != null) {
                    Toast.makeText(PreferencesActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                }
                break;
            case MSG_OAUTH_SUCCESS:
            	try {
                    dismissDialog(DIALOG_PERFORMING_OAUTH);
            	} catch (Exception e) {
            		Log.d(TAG, "Caught MSG_OAUTH_SUCCESS exception " + e.getMessage());
            	}
                mUseOAuth.setChecked(true);
                break;
            }
        }
    };

    private Runnable mDoOAuth = new Runnable() {
        public void run() {
                String msg = mOAuthService.doOAuth();
                mHandler.sendMessage(mHandler.obtainMessage(MSG_OAUTH_DONE, msg));
        }
    };
    private Runnable mCallbackOAuth = new Runnable() {
        public void run() {
                Uri uri = getIntent().getData();
                String msg = mOAuthService.callbackOAuth(uri);
                if (msg == null) {
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_OAUTH_SUCCESS, msg));
                } else {
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_OAUTH_DONE, msg));
                }
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_PERFORMING_OAUTH:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle(R.string.dialog_title_performing_oauth);
            mProgressDialog.setMessage(getText(R.string.dialog_summary_performing_oauth));
            return mProgressDialog;

        default:
            return super.onCreateDialog(id);
        }
    };
}